<template>
	<div style="border: 1px solid #ccc">
		<Toolbar style="border-bottom: 1px solid #ccc" :editor="editorRef" :defaultConfig="toolbarConfig" />
		<Editor style="height: 500px; overflow-y: hidden;" v-model="valueHtml" :defaultConfig="editorConfig"
			@onCreated="handleCreated" />
	</div>
</template>

<script setup lang="ts">
import '@wangeditor/editor/dist/css/style.css' // 引入 css

import { onBeforeUnmount, shallowRef } from 'vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { IEditorConfig, IToolbarConfig } from '@wangeditor/editor'

// 父组件传参
const valueHtml = defineModel({ default: '' })

// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef()

/* 菜单栏和编辑器的配置 */
const toolbarConfig: Partial<IToolbarConfig> = {}
const editorConfig: Partial<IEditorConfig> = {
	placeholder: '请输入内容...',
	MENU_CONF: {
		uploadImage: {
			server: '/api/upload/uploadFileWithWangEditor', //上传路径
			fieldName: 'file', //form-data
			maxNumberOfFiles: 10, //最多可上传几个文件，默认为 100
			headers: {  // 自定义增加 http  header
				Authorization: localStorage.getItem('TOKEN')
			},
			allowedFileTypes: ['image/*'], //选择文件时的类型限制
			timeout: 10000
		}
	}
}

const handleCreated = (editor) => {
	editorRef.value = editor // 记录 editor 实例，重要！
}

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
	const editor = editorRef.value
	if (editor == null) return
	editor.destroy()
})
</script>   

<style scoped></style>